{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 0
   },
   "source": [
    "# Implementation of Recurrent Neural Networks from Scratch\n",
    ":label:`sec_rnn_scratch`\n",
    "\n",
    "In this section we will implement an RNN\n",
    "from scratch\n",
    "for a character-level language model,\n",
    "according to our descriptions\n",
    "in :numref:`sec_rnn`.\n",
    "Such a model\n",
    "will be trained on H. G. Wells' *The Time Machine*.\n",
    "As before, we start by reading the dataset first, which is introduced in :numref:`sec_language_model`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load ../utils/djl-imports\n",
    "%load ../utils/plot-utils\n",
    "%load ../utils/Functions.java\n",
    "%load ../utils/PlotUtils.java\n",
    "\n",
    "%load ../utils/StopWatch.java\n",
    "%load ../utils/Accumulator.java\n",
    "%load ../utils/Animator.java\n",
    "%load ../utils/Training.java\n",
    "%load ../utils/timemachine/Vocab.java\n",
    "%load ../utils/timemachine/RNNModelScratch.java\n",
    "%load ../utils/timemachine/TimeMachine.java\n",
    "%load ../utils/timemachine/SeqDataLoader.java"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@FunctionalInterface\n",
    "public interface TriFunction<T, U, V, W> {\n",
    "    public W apply(T t, U u, V v);\n",
    "}\n",
    "\n",
    "@FunctionalInterface\n",
    "public interface QuadFunction<T, U, V, W, R> {\n",
    "    public R apply(T t, U u, V v, W w);\n",
    "}\n",
    "\n",
    "@FunctionalInterface\n",
    "public interface SimpleFunction<T> {\n",
    "    public T apply();\n",
    "}\n",
    "\n",
    "@FunctionalInterface\n",
    "public interface voidFunction<T> {\n",
    "    public void apply(T t);\n",
    "}\n",
    "\n",
    "@FunctionalInterface\n",
    "public interface voidTwoFunction<T, U> {\n",
    "    public void apply(T t, U u);\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "NDManager manager = NDManager.newBaseManager();"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "int batchSize = 32;\n",
    "int numSteps = 35;\n",
    "Pair<List<NDList>, Vocab> timeMachine = SeqDataLoader.loadDataTimeMachine(batchSize, numSteps, false, 10000, manager);\n",
    "List<NDList> trainIter = timeMachine.getKey();\n",
    "Vocab vocab = timeMachine.getValue();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 6
   },
   "source": [
    "## One-Hot Encoding\n",
    "\n",
    "Recall that each token is represented as a numerical index in `trainIter`.\n",
    "Feeding these indices directly to a neural network might make it hard to\n",
    "learn.\n",
    "We often represent each token as a more expressive feature vector.\n",
    "The easiest representation is called *one-hot encoding*,\n",
    "which is introduced\n",
    "in :numref:`subsec_classification-problem`.\n",
    "\n",
    "In a nutshell, we map each index to a different unit vector: assume that the number of different tokens in the vocabulary is $N$ (`vocab.length()`) and the token indices range from 0 to $N-1$.\n",
    "If the index of a token is the integer $i$, then we create a vector of all 0s with a length of $N$ and set the element at position $i$ to 1.\n",
    "This vector is the one-hot vector of the original token. The one-hot vectors with indices 0 and 2 are shown below.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "manager.create(new int[] {0, 2}).oneHot(vocab.length()).toDevice(Functions.tryGpu(0), false)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 10
   },
   "source": [
    "The shape of the minibatch that we sample each time is (batch size, number of time steps).\n",
    "The `oneHot` function transforms such a minibatch into a three-dimensional NDArray with the last dimension equals to the vocabulary size (`vocab.length()`).\n",
    "We often transpose the input so that we will obtain an\n",
    "output of shape\n",
    "(number of time steps, batch size, vocabulary size).\n",
    "This will allow us\n",
    "to more conveniently\n",
    "loop through the outermost dimension\n",
    "for updating hidden states of a minibatch,\n",
    "time step by time step.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDArray X = manager.arange(10).reshape(new Shape(2,5));\n",
    "X.transpose().oneHot(28).getShape()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 14
   },
   "source": [
    "## Initializing the Model Parameters\n",
    "\n",
    "Next, we initialize the model parameters for\n",
    "the RNN model.\n",
    "The number of hidden units `numHiddens` is a tunable hyperparameter.\n",
    "When training language models,\n",
    "the inputs and outputs are from the same vocabulary.\n",
    "Hence, they have the same dimension,\n",
    "which is equal to the vocabulary size.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public static NDList getParams(int vocabSize, int numHiddens, Device device) {\n",
    "    int numOutputs = vocabSize;\n",
    "    int numInputs = vocabSize;\n",
    "\n",
    "    // Hidden layer parameters\n",
    "    NDArray W_xh = normal(new Shape(numInputs, numHiddens), device);\n",
    "    NDArray W_hh = normal(new Shape(numHiddens, numHiddens), device);\n",
    "    NDArray b_h = manager.zeros(new Shape(numHiddens), DataType.FLOAT32, device);\n",
    "    // Output layer parameters\n",
    "    NDArray W_hq = normal(new Shape(numHiddens, numOutputs), device);\n",
    "    NDArray b_q = manager.zeros(new Shape(numOutputs), DataType.FLOAT32, device);\n",
    "\n",
    "    // Attach gradients\n",
    "    NDList params = new NDList(W_xh, W_hh, b_h, W_hq, b_q);\n",
    "    for (NDArray param : params) {\n",
    "        param.setRequiresGradient(true);\n",
    "    }\n",
    "    return params;\n",
    "}\n",
    "\n",
    "public static NDArray normal(Shape shape, Device device) {\n",
    "    return manager.randomNormal(0f, 0.01f, shape, DataType.FLOAT32, device);\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 18
   },
   "source": [
    "## RNN Model\n",
    "\n",
    "To define an RNN model,\n",
    "we first need an `initRNNState` function\n",
    "to return the hidden state at initialization.\n",
    "It returns a NDArray filled with 0 and with a shape of (batch size, number of hidden units).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public static NDList initRNNState(int batchSize, int numHiddens, Device device) {\n",
    "    return new NDList(manager.zeros(new Shape(batchSize, numHiddens), DataType.FLOAT32, device));\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 22
   },
   "source": [
    "The following `rnn` function defines how to compute the hidden state and output\n",
    "at a time step.\n",
    "Note that\n",
    "the RNN model\n",
    "loops through the outermost dimension of `inputs`\n",
    "so that it updates hidden states `H` of a minibatch,\n",
    "time step by time step.\n",
    "Besides,\n",
    "the activation function here uses the $\\tanh$ function.\n",
    "As\n",
    "described in :numref:`sec_mlp`, the\n",
    "mean value of the $\\tanh$ function is 0, when the elements are uniformly\n",
    "distributed over the real numbers.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public static Pair<NDArray, NDList> rnn(NDArray inputs, NDList state, NDList params) {\n",
    "    // Shape of `inputs`: (`numSteps`, `batchSize`, `vocabSize`)\n",
    "    NDArray W_xh = params.get(0);\n",
    "    NDArray W_hh = params.get(1);\n",
    "    NDArray b_h = params.get(2);\n",
    "    NDArray W_hq = params.get(3);\n",
    "    NDArray b_q = params.get(4);\n",
    "    NDArray H = state.get(0);\n",
    "\n",
    "    NDList outputs = new NDList();\n",
    "    // Shape of `X`: (`batchSize`, `vocabSize`)\n",
    "    NDArray X, Y;\n",
    "    for (int i = 0; i < inputs.size(0); i++) {\n",
    "        X = inputs.get(i);\n",
    "        H = (X.dot(W_xh).add(H.dot(W_hh)).add(b_h)).tanh();\n",
    "        Y = H.dot(W_hq).add(b_q);\n",
    "        outputs.add(Y);\n",
    "    }\n",
    "    return new Pair<>(outputs.size() > 1 ? NDArrays.concat(outputs) : outputs.get(0), new NDList(H));\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 26
   },
   "source": [
    "With all the needed functions being defined,\n",
    "next we create a class to wrap these functions and store parameters for an RNN model implemented from scratch.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "/** An RNN Model implemented from scratch. */\n",
    "public class RNNModelScratch {\n",
    "    public int vocabSize;\n",
    "    public int numHiddens;\n",
    "    public NDList params;\n",
    "    public TriFunction<Integer, Integer, Device, NDList> initState;\n",
    "    public TriFunction<NDArray, NDList, NDList, Pair> forwardFn;\n",
    "\n",
    "    public RNNModelScratch(\n",
    "            int vocabSize,\n",
    "            int numHiddens,\n",
    "            Device device,\n",
    "            TriFunction<Integer, Integer, Device, NDList> getParams,\n",
    "            TriFunction<Integer, Integer, Device, NDList> initRNNState,\n",
    "            TriFunction<NDArray, NDList, NDList, Pair> forwardFn) {\n",
    "        this.vocabSize = vocabSize;\n",
    "        this.numHiddens = numHiddens;\n",
    "        this.params = getParams.apply(vocabSize, numHiddens, device);\n",
    "        this.initState = initRNNState;\n",
    "        this.forwardFn = forwardFn;\n",
    "    }\n",
    "\n",
    "    public Pair forward(NDArray X, NDList state) {\n",
    "        X = X.transpose().oneHot(this.vocabSize);\n",
    "        return this.forwardFn.apply(X, state, this.params);\n",
    "    }\n",
    "\n",
    "    public NDList beginState(int batchSize, Device device) {\n",
    "        return this.initState.apply(batchSize, this.numHiddens, device);\n",
    "    }\n",
    "}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 30
   },
   "source": [
    "Let us check whether the outputs have the correct shapes, e.g., to ensure that the dimensionality of the hidden state remains unchanged.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "int numHiddens = 512;\n",
    "TriFunction<Integer, Integer, Device, NDList> getParamsFn = (a, b, c) -> getParams(a, b, c);\n",
    "TriFunction<Integer, Integer, Device, NDList> initRNNStateFn =\n",
    "        (a, b, c) -> initRNNState(a, b, c);\n",
    "TriFunction<NDArray, NDList, NDList, Pair> rnnFn = (a, b, c) -> rnn(a, b, c);\n",
    "\n",
    "NDArray X = manager.arange(10).reshape(new Shape(2, 5));\n",
    "\n",
    "RNNModelScratch net =\n",
    "        new RNNModelScratch(\n",
    "                vocab.length(), numHiddens, Functions.tryGpu(0), getParamsFn, initRNNStateFn, rnnFn);\n",
    "NDList state = net.beginState((int) X.getShape().getShape()[0], Functions.tryGpu(0));\n",
    "Pair<NDArray, NDList> pairResult = net.forward(X.toDevice(Functions.tryGpu(0), false), state);\n",
    "NDArray Y = pairResult.getKey();\n",
    "NDList newState = pairResult.getValue();\n",
    "System.out.println(Y.getShape());\n",
    "System.out.println(newState.get(0).getShape());"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 34
   },
   "source": [
    "We can see that the output shape is (number of time steps $\\times$ batch size, vocabulary size), while the hidden state shape remains the same, i.e., (batch size, number of hidden units).\n",
    "\n",
    "\n",
    "## Prediction\n",
    "\n",
    "Let us first define the prediction function\n",
    "to generate new characters following\n",
    "the user-provided `prefix`,\n",
    "which is a string containing several characters.\n",
    "When looping through these beginning characters in `prefix`,\n",
    "we keep passing the hidden state\n",
    "to the next time step without\n",
    "generating any output.\n",
    "This is called the *warm-up* period,\n",
    "during which the model updates itself\n",
    "(e.g., update the hidden state)\n",
    "but does not make predictions.\n",
    "After the warm-up period,\n",
    "the hidden state is generally better than\n",
    "its initialized value at the beginning.\n",
    "So we generate the predicted characters and emit them.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "/** Generate new characters following the `prefix`. */\n",
    "public static String predictCh8(\n",
    "        String prefix, int numPreds, RNNModelScratch net, Vocab vocab, Device device) {\n",
    "    NDList state = net.beginState(1, device);\n",
    "    List<Integer> outputs = new ArrayList<>();\n",
    "    outputs.add(vocab.getIdx(\"\" + prefix.charAt(0)));\n",
    "    SimpleFunction<NDArray> getInput =\n",
    "            () ->\n",
    "                    manager.create(outputs.get(outputs.size() - 1))\n",
    "                            .toDevice(device, false)\n",
    "                            .reshape(new Shape(1, 1));\n",
    "    for (char c : prefix.substring(1).toCharArray()) { // Warm-up period\n",
    "        state = (NDList) net.forward(getInput.apply(), state).getValue();\n",
    "        outputs.add(vocab.getIdx(\"\" + c));\n",
    "    }\n",
    "\n",
    "    NDArray y;\n",
    "    for (int i = 0; i < numPreds; i++) {\n",
    "        Pair<NDArray, NDList> pair = net.forward(getInput.apply(), state);\n",
    "        y = pair.getKey();\n",
    "        state = pair.getValue();\n",
    "\n",
    "        outputs.add((int) y.argMax(1).reshape(new Shape(1)).getLong(0L));\n",
    "    }\n",
    "    StringBuilder output = new StringBuilder();\n",
    "    for (int i : outputs) {\n",
    "        output.append(vocab.idxToToken.get(i));\n",
    "    }\n",
    "    return output.toString();\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 38
   },
   "source": [
    "Now we can test the `predict_ch8` function.\n",
    "We specify the prefix as `time traveller ` and have it generate 10 additional characters.\n",
    "Given that we have not trained the network,\n",
    "it will generate nonsensical predictions.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "predictCh8(\"time traveller \", 10, net, vocab, Functions.tryGpu(0));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 41
   },
   "source": [
    "## Gradient Clipping\n",
    "\n",
    "For a sequence of length $T$,\n",
    "we compute the gradients over these $T$ time steps in an iteration, which results in a chain of matrix-products with length  $\\mathcal{O}(T)$ during backpropagation.\n",
    "As mentioned in :numref:`sec_numerical_stability`, it might result in numerical instability, e.g., the gradients may either explode or vanish, when $T$ is large. Therefore, RNN models often need extra help to stabilize the training.\n",
    "\n",
    "Generally speaking,\n",
    "when solving an optimization problem,\n",
    "we take update steps for the model parameter,\n",
    "say in the vector form\n",
    "$\\mathbf{x}$,\n",
    "in the direction of the negative gradient $\\mathbf{g}$ on a minibatch.\n",
    "For example,\n",
    "with $\\eta > 0$ as the learning rate,\n",
    "in one iteration we update\n",
    "$\\mathbf{x}$\n",
    "as $\\mathbf{x} - \\eta \\mathbf{g}$.\n",
    "Let us further assume that the objective function $f$\n",
    "is well behaved, say, *Lipschitz continuous* with constant $L$.\n",
    "That is to say,\n",
    "for any $\\mathbf{x}$ and $\\mathbf{y}$ we have\n",
    "\n",
    "$$|f(\\mathbf{x}) - f(\\mathbf{y})| \\leq L \\|\\mathbf{x} - \\mathbf{y}\\|.$$\n",
    "\n",
    "In this case we can safely assume that if we update the parameter vector by $\\eta \\mathbf{g}$, then\n",
    "\n",
    "$$|f(\\mathbf{x}) - f(\\mathbf{x} - \\eta\\mathbf{g})| \\leq L \\eta\\|\\mathbf{g}\\|,$$\n",
    "\n",
    "which means that\n",
    "we will not observe a change by more than $L \\eta \\|\\mathbf{g}\\|$. This is both a curse and a blessing.\n",
    "On the curse side,\n",
    "it limits the speed of making progress;\n",
    "whereas on the blessing side,\n",
    "it limits the extent to which things can go wrong if we move in the wrong direction.\n",
    "\n",
    "Sometimes the gradients can be quite large and the optimization algorithm may fail to converge. We could address this by reducing the learning rate $\\eta$. But what if we only *rarely* get large gradients? In this case such an approach may appear entirely unwarranted. One popular alternative is to clip the gradient $\\mathbf{g}$ by projecting them back to a ball of a given radius, say $\\theta$ via\n",
    "\n",
    "$$\\mathbf{g} \\leftarrow \\min\\left(1, \\frac{\\theta}{\\|\\mathbf{g}\\|}\\right) \\mathbf{g}.$$\n",
    "\n",
    "By doing so we know that the gradient norm never exceeds $\\theta$ and that the\n",
    "updated gradient is entirely aligned with the original direction of $\\mathbf{g}$.\n",
    "It also has the desirable side-effect of limiting the influence any given\n",
    "minibatch (and within it any given sample) can exert on the parameter vector. This\n",
    "bestows a certain degree of robustness to the model. Gradient clipping provides\n",
    "a quick fix to the gradient exploding. While it does not entirely solve the problem, it is one of the many techniques to alleviate it.\n",
    "\n",
    "Below we define a function to clip the gradients of\n",
    "a model that is implemented from scratch or a model constructed by the high-level APIs.\n",
    "Also note that we compute the gradient norm over all the model parameters.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "/** Clip the gradient. */\n",
    "public static void gradClipping(RNNModelScratch net, int theta, NDManager manager) {\n",
    "    double result = 0;\n",
    "    for (NDArray p : net.params) {\n",
    "        NDArray gradient = p.getGradient();\n",
    "        gradient.attach(manager);\n",
    "        result += gradient.pow(2).sum().getFloat();\n",
    "    }\n",
    "    double norm = Math.sqrt(result);\n",
    "    if (norm > theta) {\n",
    "        for (NDArray param : net.params) {\n",
    "            NDArray gradient = param.getGradient();\n",
    "            gradient.muli(theta / norm);\n",
    "        }\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 45
   },
   "source": [
    "## Training\n",
    "\n",
    "Before training the model,\n",
    "let us define a function to train the model in one epoch. It differs from how we train the model of :numref:`sec_softmax_scratch` in three places:\n",
    "\n",
    "1. Different sampling methods for sequential data (random sampling and sequential partitioning) will result in differences in the initialization of hidden states.\n",
    "1. We clip the gradients before updating the model parameters. This ensures that the model does not diverge even when gradients blow up at some point during the training process.\n",
    "1. We use perplexity to evaluate the model. As discussed in :numref:`subsec_perplexity`, this ensures that sequences of different length are comparable.\n",
    "\n",
    "\n",
    "Specifically,\n",
    "when sequential partitioning is used, we initialize the hidden state only at the beginning of each epoch.\n",
    "Since the $i^\\mathrm{th}$ subsequence example  in the next minibatch is adjacent to the current $i^\\mathrm{th}$ subsequence example,\n",
    "the hidden state at the end of the current minibatch\n",
    "will be\n",
    "used to initialize\n",
    "the hidden state at the beginning of the next minibatch.\n",
    "In this way,\n",
    "historical information of the sequence\n",
    "stored in the hidden state\n",
    "might flow over\n",
    "adjacent subsequences within an epoch.\n",
    "However, the computation of the hidden state\n",
    "at any point depends on all the previous minibatches\n",
    "in the same epoch,\n",
    "which complicates the gradient computation.\n",
    "To reduce computational cost,\n",
    "we detach the gradient before processing any minibatch\n",
    "so that the gradient computation of the hidden state\n",
    "is always limited to\n",
    "the time steps in one minibatch. \n",
    "\n",
    "When using the random sampling,\n",
    "we need to re-initialize the hidden state for each iteration since each example is sampled with a random position.\n",
    "Same as the `trainEpochCh3` function in :numref:`sec_softmax_scratch`,\n",
    "`updater` is a general function\n",
    "to update the model parameters.\n",
    "It can be either the function implemented from scratch or the built-in optimization function in\n",
    "a deep learning framework.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "/** Train a model within one epoch. */\n",
    "public static Pair<Double, Double> trainEpochCh8(\n",
    "        RNNModelScratch net,\n",
    "        List<NDList> trainIter,\n",
    "        Loss loss,\n",
    "        voidTwoFunction<Integer, NDManager> updater,\n",
    "        Device device,\n",
    "        boolean useRandomIter) {\n",
    "    StopWatch watch = new StopWatch();\n",
    "    watch.start();\n",
    "    Accumulator metric = new Accumulator(2); // Sum of training loss, no. of tokens\n",
    "    try (NDManager childManager = manager.newSubManager()) {\n",
    "        NDList state = null;\n",
    "        for (NDList pair : trainIter) {\n",
    "            NDArray X = pair.get(0).toDevice(Functions.tryGpu(0), true);\n",
    "            X.attach(childManager);\n",
    "            NDArray Y = pair.get(1).toDevice(Functions.tryGpu(0), true);\n",
    "            Y.attach(childManager);\n",
    "            if (state == null || useRandomIter) {\n",
    "                // Initialize `state` when either it is the first iteration or\n",
    "                // using random sampling\n",
    "                state = net.beginState((int) X.getShape().getShape()[0], device);\n",
    "            } else {\n",
    "                for (NDArray s : state) {\n",
    "                    s.stopGradient();\n",
    "                }\n",
    "            }\n",
    "            state.attach(childManager);\n",
    "\n",
    "            NDArray y = Y.transpose().reshape(new Shape(-1));\n",
    "            X = X.toDevice(device, false);\n",
    "            y = y.toDevice(device, false);\n",
    "            try (GradientCollector gc = Engine.getInstance().newGradientCollector()) {\n",
    "                Pair<NDArray, NDList> pairResult = net.forward(X, state);\n",
    "                NDArray yHat = pairResult.getKey();\n",
    "                state = pairResult.getValue();\n",
    "                NDArray l = loss.evaluate(new NDList(y), new NDList(yHat)).mean();\n",
    "                gc.backward(l);\n",
    "                metric.add(new float[] {l.getFloat() * y.size(), y.size()});\n",
    "            }\n",
    "            gradClipping(net, 1, childManager);\n",
    "            updater.apply(1, childManager); // Since the `mean` function has been invoked\n",
    "        }\n",
    "    }\n",
    "    return new Pair<>(Math.exp(metric.get(0) / metric.get(1)), metric.get(1) / watch.stop());\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 49
   },
   "source": [
    "The training function supports\n",
    "an RNN model implemented\n",
    "either from scratch\n",
    "or using high-level APIs.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "/** Train a model. */\n",
    "    public static void trainCh8(\n",
    "            RNNModelScratch net,\n",
    "            List<NDList> trainIter,\n",
    "            Vocab vocab,\n",
    "            int lr,\n",
    "            int numEpochs,\n",
    "            Device device,\n",
    "            boolean useRandomIter) {\n",
    "        SoftmaxCrossEntropyLoss loss = new SoftmaxCrossEntropyLoss();\n",
    "        Animator animator = new Animator();\n",
    "        // Initialize\n",
    "        voidTwoFunction<Integer, NDManager> updater =\n",
    "                (batchSize, subManager) -> Training.sgd(net.params, lr, batchSize, subManager);\n",
    "        Function<String, String> predict = (prefix) -> predictCh8(prefix, 50, net, vocab, device);\n",
    "        // Train and predict\n",
    "        double ppl = 0.0;\n",
    "        double speed = 0.0;\n",
    "        for (int epoch = 0; epoch < numEpochs; epoch++) {\n",
    "            Pair<Double, Double> pair =\n",
    "                    trainEpochCh8(net, trainIter, loss, updater, device, useRandomIter);\n",
    "            ppl = pair.getKey();\n",
    "            speed = pair.getValue();\n",
    "            if ((epoch + 1) % 10 == 0) {\n",
    "                animator.add(epoch + 1, (float) ppl, \"\");\n",
    "                animator.show();\n",
    "            }\n",
    "        }\n",
    "        System.out.format(\n",
    "                \"perplexity: %.1f, %.1f tokens/sec on %s%n\", ppl, speed, device.toString());\n",
    "        System.out.println(predict.apply(\"time traveller\"));\n",
    "        System.out.println(predict.apply(\"traveller\"));\n",
    "    }"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 53
   },
   "source": [
    "Now we can train the RNN model.\n",
    "Since we only use 10000 tokens in the dataset, the model needs more epochs to converge better.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "int numEpochs = Integer.getInteger(\"MAX_EPOCH\", 500);\n",
    "\n",
    "int lr = 1;\n",
    "trainCh8(net, trainIter, vocab, lr, numEpochs, Functions.tryGpu(0), false);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 56
   },
   "source": [
    "Finally,\n",
    "let us check the results of using the random sampling method.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "trainCh8(net, trainIter, vocab, lr, numEpochs, Functions.tryGpu(0), true);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 59
   },
   "source": [
    "While implementing the above RNN model from scratch is instructive, it is not convenient.\n",
    "In the next section we will see how to improve the RNN model,\n",
    "such as how to make it easier to implement\n",
    "and make it run faster.\n",
    "\n",
    "\n",
    "## Summary\n",
    "\n",
    "* We can train an RNN-based character-level language model to generate text following the user-provided text prefix.\n",
    "* A simple RNN language model consists of input encoding, RNN modeling, and output generation.\n",
    "* RNN models need state initialization for training, though random sampling and sequential partitioning use different ways.\n",
    "* When using sequential partitioning, we need to detach the gradient to reduce computational cost.\n",
    "* A warm-up period allows a model to update itself (e.g., obtain a better hidden state than its initialized value) before making any prediction.\n",
    "* Gradient clipping prevents gradient explosion, but it cannot fix vanishing gradients.\n",
    "\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Show that one-hot encoding is equivalent to picking a different embedding for each object.\n",
    "1. Adjust the hyperparameters (e.g., number of epochs, number of hidden units, number of time steps in a minibatch, and learning rate) to improve the perplexity.\n",
    "    * How low can you go?\n",
    "    * Replace one-hot encoding with learnable embeddings. Does this lead to better performance?\n",
    "    * How well will it work on other books by H. G. Wells, e.g., [*The War of the Worlds*](http://www.gutenberg.org/ebooks/36)?\n",
    "1. Modify the prediction function such as to use sampling rather than picking the most likely next character.\n",
    "    * What happens?\n",
    "    * Bias the model towards more likely outputs, e.g., by sampling from $q(x_t \\mid x_{t-1}, \\ldots, x_1) \\propto P(x_t \\mid x_{t-1}, \\ldots, x_1)^\\alpha$ for $\\alpha > 1$.\n",
    "1. Run the code in this section without clipping the gradient. What happens?\n",
    "1. Change sequential partitioning so that it does not separate hidden states from the computational graph. Does the running time change? How about the perplexity?\n",
    "1. Replace the activation function used in this section with ReLU and repeat the experiments in this section. Do we still need gradient clipping? Why?\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Java",
   "language": "java",
   "name": "java"
  },
  "language_info": {
   "codemirror_mode": "java",
   "file_extension": ".jshell",
   "mimetype": "text/x-java-source",
   "name": "Java",
   "pygments_lexer": "java",
   "version": "14.0.2+12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
